package util
{

	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.getTimer;

	import globals.Global;

	import manager.TimerManager;

	/**
	 * 自定义－计时器
	 * @author l uguobin
	 */
	public class GameTimer extends EventDispatcher
	{
		private var _currentCount:int;
		private var _delay:Number;
		private var _repeatCount:int;
		private var _running:Boolean;
		private var _startTime:int; //开始时间。
		private var _currentTime:int; //当前时间。

		/**使用指定的 delay 和 repeatCount 状态构造新的 Timer 对象。**/
		public function GameTimer(delay:Number, repeatCount:int = 0)
		{
			_delay = delay;
			_repeatCount = repeatCount;
		}

		/**如果计时器正在运行，则停止计时器，并将 currentCount 属性设回为 0，这类似于秒表的重置按钮。**/
		public function reset():void
		{
			_currentCount = 0;
			_startTime = 0;
			stop();
		}

		/**如果计时器尚未运行，则启动计时器。**/
		public function start():void
		{
			_startTime = getTimer();
			_running = true;
			TimerManager.addTimer(this);
		}

		/**停止计时器。**/
		public function stop():void
		{
			if(_running)
			{
				_running = false;
				TimerManager.removeTimer(this);
			}
		}

		public function enterFrame():void
		{
			if(_running)
			{
				_currentTime = Global.timeStamp;
				var len:int = (_currentTime - _startTime) / _delay;

				if(len >= 1)
				{
					for(var i:int = 0; i < len; i++)
					{
						_currentCount++;

						if(_repeatCount > 0 && _repeatCount <= _currentCount)
						{
							stop();
							stepRun();

							if(this.hasEventListener(TimerEvent.TIMER_COMPLETE))
							{
								this.dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
							}
							break;
						}
						else
						{
							stepRun();
						}
					}
				}
			}
		}

		private function stepRun():void
		{
			_startTime += _delay;

			if(this.hasEventListener(TimerEvent.TIMER))
			{
				this.dispatchEvent(new TimerEvent(TimerEvent.TIMER));
			}
		}

		/**[] 计时器从 0 开始后触发的总次数。**/
		public function get currentCount():int
		{
			return _currentCount;
		}

		/**计时器事件间的延迟（以毫秒为单位）。**/
		public function get delay():Number
		{
			return _delay;
		}

		/**
		 * @private
		 */
		public function set delay(value:Number):void
		{
			_delay = value;
		}

		/**设置的计时器运行总次数。**/
		public function get repeatCount():int
		{
			return _repeatCount;
		}

		public function set repeatCount(value:int):void
		{
			_repeatCount = value;
		}

		/**[] 计时器的当前状态；如果计时器正在运行，则为 true，否则为 false。**/
		public function get running():Boolean
		{
			return _running;
		}
	}
}